#include <Windows.h>
#include <WindowsX.h>
#include <tchar.h>
#include "resource.h"

struct SEventInfo {
	HANDLE		hEvent;
	HWND		hList;
};

DWORD CALLBACK ThreadProc(LPVOID lpData)
{
	SEventInfo* pEvtInfo = (SEventInfo*)lpData;
	if (NULL != pEvtInfo)
	{
		TCHAR szTmp[MAX_PATH];
		DWORD dwCount = 0;
		DWORD dwAction = INFINITE;
		while (true)
		{
			DWORD dwWait = WaitForSingleObject(pEvtInfo->hEvent, dwAction);
			switch (dwWait)
			{	
				case WAIT_OBJECT_0: dwAction = (dwCount == 0) ? 0 : INFINITE;	break;
				case WAIT_TIMEOUT: dwAction = 0;	break;
			}
			_stprintf(szTmp, _T("print %04d line"), dwCount = (dwCount > 10000) ? 1 : ++dwCount);
			ListBox_AddString(pEvtInfo->hList, szTmp);
			SendMessage(pEvtInfo->hList, WM_VSCROLL, SB_BOTTOM, 0);
		}
	}

	return 0;
}

int CALLBACK DlgProc(HWND hDlg, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
	static HANDLE hEvent = NULL;
	static SEventInfo EvtInfo;
	switch (nMsg)
	{
		case WM_INITDIALOG:
		{
			SetWindowText(hDlg, _T("Demo0091"));

			UINT nWidth		= GetSystemMetrics(SM_CXSCREEN);
			UINT nHeight	= GetSystemMetrics(SM_CYSCREEN);
			RECT rtClient;
			GetClientRect(hDlg, &rtClient);
			SetWindowPos(hDlg, NULL, (nWidth - (rtClient.right - rtClient.left)) / 2, (nHeight - (rtClient.bottom - rtClient.top)) / 2, 0, 0, SWP_NOSIZE);
			
			hEvent			= CreateEvent(NULL, TRUE, FALSE, NULL);
			EvtInfo.hEvent	= hEvent;
			EvtInfo.hList	= GetDlgItem(hDlg, IDC_LIST1);
			CreateThread(NULL, 0, ThreadProc, (LPVOID)&EvtInfo, 0, NULL);
			break;
		}
		case WM_COMMAND:
		{
			switch (LOWORD(wParam))
			{
				case IDC_BTNACTION:
				{
					TCHAR szName[MAX_PATH];
					GetDlgItemText(hDlg, IDC_BTNACTION, szName, MAX_PATH);
					if (0 == _tcsicmp(szName, _T("Start")))
					{
						SetDlgItemText(hDlg, IDC_BTNACTION, _T("Stop"));
						SetEvent(hEvent);
					} else {
						SetDlgItemText(hDlg, IDC_BTNACTION, _T("Start"));
						ResetEvent(hEvent);
					}
					break;
				}
			}
			break;
		}
		case WM_CLOSE:
		{
			PostQuitMessage(0);
			break;
		}
	}

	return 0;
}

BOOL WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPreInstance, LPTSTR szCmdLine, int nShowCmd)
{
	HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, _T("FD555BF5-1BC2-4636-AA8F-1D9BC9E253F9"));
	if (NULL != hEvent && GetLastError() == ERROR_ALREADY_EXISTS)
	{
		MessageBox(NULL, _T("Demo0091 is running..."), _T("Demo0091"), MB_OK);
		return FALSE;
	}

	DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG), NULL, DlgProc);

	return TRUE;
}